package com.xunkids.bos.migration.component.log.impl;


import cn.hutool.core.thread.NamedThreadFactory;
import cn.hutool.core.thread.ThreadUtil;
import com.xunkids.bos.migration.component.log.LogService;
import com.xunkids.bos.migration.component.log.LoggerHelp;
import com.xunkids.bos.migration.component.log.MigrationLog;
import org.slf4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * log4j2 日志
 *
 * @author baiyanlong
 * @version 1.0.0
 * @since 2022/10/28 15:32
 */
public class Log4j2LogService implements LogService, InitializingBean {

    /**
     * 默认日志
     */
    private final Logger defLog = LoggerHelp.getLogger("file-logger");

    /**
     * 日志 map
     */
    private final Map<String, Logger> loggerMap;

    /**
     * 日志
     */

    /**
     * 线程池
     */
    private final ThreadPoolExecutor executor;

    public Log4j2LogService(int loggerMapCapacity, int threadNum) {
        loggerMap = new ConcurrentHashMap<>(loggerMapCapacity);
        executor = new ThreadPoolExecutor(threadNum, threadNum, 60L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), new NamedThreadFactory("log-file-", false));
    }

    /**
     * 发送
     *
     * @param log 日志
     */
    @Override
    public void save(MigrationLog log) {

    }

    /**
     * 批量保存
     *
     * @param logs 日志集
     */
    @Override
    public void save(List<MigrationLog> logs) {

    }


    private void write(Logger logger, String level, String text) {
        switch (level.toLowerCase(Locale.ROOT)) {
            case "trace":
                if (logger.isTraceEnabled()) {
                    logger.trace(text);
                }
                break;
            case "debug":
                if (logger.isDebugEnabled()) {
                    logger.debug(text);
                }
                break;
            case "info":
                if (logger.isInfoEnabled()) {
                    logger.info(text);
                }
                break;
            case "warn":
                if (logger.isWarnEnabled()) {
                    logger.warn(text);
                }
                break;
            case "error":
                if (logger.isErrorEnabled()) {
                    logger.error(text);
                }
                break;
            default:
                if (defLog.isInfoEnabled()) {
                    defLog.info("默认 {} ", text);
                }
                break;
        }
    }

    private void run() {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        new Thread(this::run, "file-log").start();
    }
}
